package com.zbkj.common.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.jcraft.jsch.*;
import com.zbkj.common.constants.UploadConstants;
import com.zbkj.common.exception.CrmebException;
import org.apache.commons.io.FilenameUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 上传工具类
 * +----------------------------------------------------------------------
 * | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2016~2025 https://www.crmeb.com All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
 * +----------------------------------------------------------------------
 * | Author: CRMEB Team <admin@crmeb.com>
 * +----------------------------------------------------------------------
 */
public class UploadUtil {

    //服务器存储地址
    private static String rootPath = "";
    //类型
    private static String type = "/" + UploadConstants.UPLOAD_FILE_KEYWORD;
    //模块
    private static String modelPath = "/public";
    //扩展名
    private static String extStr = "png,jpg";
    //文件大小上限
    private static int size = 2;

    public static String getRootPath() {
        return rootPath;
    }

    public static void setRootPath(String rootPath) {
        UploadUtil.rootPath = (rootPath + "/").replace(" ", "").replace("//", "/");
    }

    public static String getType() {
        return type;
    }

    public static void setType(String type) {
        UploadUtil.type = type + "/";
    }

    public static String getModelPath() {
        return modelPath;
    }

    public static void setModelPath(String modelPath) {
        UploadUtil.modelPath = modelPath + "/";
    }

    public static String getExtStr() {
        return extStr;
    }

    public static void setExtStr(String extStr) {
        UploadUtil.extStr = extStr;
    }

    public static int getSize() {
        return size;
    }

    public static void setSize(int size) {
        UploadUtil.size = size;
    }

    /**
     * 根据文件的绝对路径创建一个文件对象.
     *
     * @return 返回创建的这个文件对象
     * @since 2020-05-08
     */
    public static File createFile(String filePath) throws IOException {
        // 获取文件的完整目录
        String fileDir = FilenameUtils.getFullPath(filePath);
        // 判断目录是否存在，不存在就创建一个目录
        File file = new File(fileDir);
        if (!file.isDirectory()) {
            //创建失败返回null
            if (!file.mkdirs()) {
                throw new CrmebException("文件目录创建失败...");
            }
        }
        // 判断这个文件是否存在，不存在就创建
        file = new File(filePath);
        if (!file.exists()) {
            if (!file.createNewFile()) {
                throw new CrmebException("目标文件创建失败...");
            }
        }
        return file;
    }

    /**
     * 生成文件文件名
     *
     * @param fileName 文件名
     * @since 2020-05-08
     */
    public static String getDestPath(String fileName) {
        //规则：  子目录/年/月/日.后缀名
        return getServerPath() + fileName;
    }

    public static String fileName(String extName) {
        return CrmebUtil.getUuid() + RandomUtil.randomString(10) + "." + extName;
    }

    /**
     * 生成文件在的实际的路径
     *
     * @since 2020-05-08
     */
    public static String getServerPath() {
        // 文件分隔符转化为当前系统的格式
        return FilenameUtils.separatorsToSystem(getRootPath() + getWebPath());
    }

    /**
     * web目录可访问的路径
     *
     * @since 2020-05-08
     */
    public static String getWebPath() {
        // 文件分隔符转化为当前系统的格式
        return getModelPath() + DateUtil.format(DateUtil.date(), "yyyy/MM/dd") + "/";
    }

    /**
     * 服务器路径
     */
    public static String hzwServerPath = "";
    /**
     * 文件路径路径
     */
    public static String hzwFilePath = "";

    public static String getHzwServerPath() {
        return hzwServerPath;
    }

    public static void setHzwServerPath(String hzwServerPath) {
        UploadUtil.hzwServerPath = hzwServerPath;
    }

    public static String getHzwFilePath() {
        return hzwFilePath;
    }

    public static void setHzwFilePath(String hzwFilePath) {
        UploadUtil.hzwFilePath = hzwFilePath;
    }

   public static void tempUpload(String localFilePath,String sftpFilePath){
       String sftpHost = "175.178.65.163";
       int sftpPort = 22; // 默认SFTP端口是22
       String sftpUser = "root";
       String sftpPassword = "yhswNo@01&zkf963539!_,";
      // String sftpFilePath  = "/home/ysfs/file/temp/" + tempSftpFilePath; // 远程SFTP路径和文件名
       System.out.println("sftpFilePath--->"+sftpFilePath);
       try {
           JSch jsch = new JSch();
           Session session = jsch.getSession(sftpUser, sftpHost, sftpPort);
           session.setConfig("StrictHostKeyChecking", "no");
           session.setPassword(sftpPassword);
           session.connect();

           Channel channel = session.openChannel("sftp");
           channel.connect();
           ChannelSftp sftpChannel = (ChannelSftp) channel;

//           //判断文件路径是否存在
//           String fileFir = sftpFilePath.substring(0, sftpFilePath.lastIndexOf('/'));
//         //  try {
//            //   sftpChannel.lstat(fileFir);
//          // }catch (Exception e){
//               sftpChannel.mkdir(fileFir);
//         //  }
           // 上传文件到远程服务器
           sftpChannel.put(localFilePath, sftpFilePath);
           System.out.println("File uploaded successfully.");

           // 关闭连接和通道
           sftpChannel.exit();
           channel.disconnect();
           session.disconnect();
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

    public static void main(String[] args) {

        String serverUrl = "http://175.178.65.163：8me/ysfs/file/crmebimage/public/content";
        String filePath = "D:\\crmebimage\\public\\content\\2025\\02\\16\\4690e3085494453891979d562de10270lkqqvxcjlx.png";

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(serverUrl);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", new File(filePath));
            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);

            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == 200) {
                System.out.println("File uploaded successfully.");
            } else {
                System.out.println("File upload failed with status code: " + statusCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
